package com.ruoyi.manage.baiduApi.impl;

import com.baidu.aip.ocr.AipOcr;
import com.ruoyi.common.utils.AipBaiDuUtils;
import com.ruoyi.manage.baiduApi.CardIdentificationApi;
import com.ruoyi.manage.baiduApi.request.CardRequest;
import com.ruoyi.manage.baiduApi.response.CardResponse;
import org.json.JSONObject;

import java.util.Map;

/**
 * @Author: wwy
 * @Date: 2021/3/3 10:10
 */
public class CardIdentificationClient implements CardIdentificationApi {

    @Override
    public CardResponse identificationExecute(CardRequest cardRequest) {
        AipOcr aipOcrClient = AipBaiDuUtils.getAipOcrClient();
        JSONObject idcardJson = aipOcrClient.idcard(cardRequest.getImage(), cardRequest.getIdCardSide(), cardRequest.getOptions());
        Map<String, Object> map = idcardJson.toMap();
        String image_status = String.valueOf(map.get("image_status"));
        CardResponse cardResponse = new CardResponse();
        if("normal".equals(image_status)){
            //成功
            cardResponse.setSuccess(true);
            if("back".equals(cardRequest.getIdCardSide())){
                //身份证带国徽的一面
                return cardResponse;
            }
            Map<String, Object> words_result = (Map<String, Object>) map.get("words_result");
            Map<String, Object> addressMap = (Map<String, Object>) words_result.get("住址");
            String address = String.valueOf(addressMap.get("words"));
            Map<String, Object> identityNumberMap = (Map<String, Object>) words_result.get("公民身份号码");
            String identityNumber = String.valueOf(identityNumberMap.get("words"));
            Map<String, Object> birthMap = (Map<String, Object>) words_result.get("出生");
            String birth = String.valueOf(birthMap.get("words"));
            Map<String, Object> nameMap = (Map<String, Object>) words_result.get("姓名");
            String name = String.valueOf(nameMap.get("words"));
            Map<String, Object> sexMap = (Map<String, Object>) words_result.get("性别");
            String sex = String.valueOf(sexMap.get("words"));
            Map<String, Object> nationalityMap = (Map<String, Object>) words_result.get("民族");
            String nationality = String.valueOf(nationalityMap.get("words"));
            cardResponse.setAddress(address);
            cardResponse.setIdentityNumber(identityNumber);
            cardResponse.setBirth(birth);
            cardResponse.setName(name);
            cardResponse.setSex(sex);
            cardResponse.setNationality(nationality);
        }else{
            //失败
            cardResponse.setSuccess(false);
        }
        return cardResponse;
    }
}
